package com.kaoshi.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaoshi.common.config.Message;
import com.kaoshi.common.config.MessageUtils;
import org.apache.catalina.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigUrator.class)
public class ChatEndpoint {

    private static Map<String,ChatEndpoint> onlineUsers=new ConcurrentHashMap<>();

    private Session session;

    private HttpSession httpSession;
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
//        this.session=session;
//        HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
//        this.httpSession=httpSession;
//
//        String user = (String) httpSession.getAttribute("username");
//        onlineUsers.put(user,this);
//        String message = MessageUtils.getMessage(true, null, getNames());
//        broadcastAllUsers(message);
//        System.out.println(11111111);
    }

    private Set<String> getNames(){
        return onlineUsers.keySet();
    }

    private void broadcastAllUsers(String message){
        try{
            Set<String> strings = onlineUsers.keySet();
            for (String string : strings) {
                ChatEndpoint chatEndpoint = onlineUsers.get(string);
                chatEndpoint.session.getAsyncRemote().sendText(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Message message1 = mapper.readValue(message, Message.class);
//        获取要发送的消息给用户
        String toName = message1.getToName();
//        获取要发送的消息内容
        String data= message1.getMessage();
        User user = (User) httpSession.getAttribute("user");
        MessageUtils.getMessage(false, user.getUsername(), data);

        onlineUsers.get(toName).session.getBasicRemote().sendText(message);
    }

    @OnClose
    public void onClose(Session session) {

    }

}
